package com.qiguliuxing.dts.admin.web;

import javax.validation.constraints.NotNull;

import com.qiguliuxing.dts.admin.dao.DocAll;
import com.qiguliuxing.dts.admin.service.AdminDocService;
import com.qiguliuxing.dts.db.domain.GmDoc;
import com.qiguliuxing.dts.db.service.GmDocModService;
import com.qiguliuxing.dts.db.service.GmDocService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.util.AuthSupport;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Random;

@RestController
@RequestMapping("/admin/doc")
@Validated
public class AdminDocController {
    private static final Logger logger = LoggerFactory.getLogger(AdminDocController.class);

    @Autowired
    private GmDocService gmDocService;

    @Autowired
    private GmDocModService gmDocModService;

    @Autowired
    private AdminDocService adminDocService;

    /**
     * 查询商品
     * 查詢文檔
     * @param
     * @param page
     * @param limit
     * @param  sort
     * @param order
     * @return
     */
    @RequiresPermissions("admin:doc:list")
    @RequiresPermissionsDesc(menu = { "文件管理", "文件列表" }, button = "查询")
    @GetMapping("/list")
    public Object list(String docNumber,String docName,@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "8") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 文件管理->文件管理->查询,请求参数:docNumber:{},docName:{},page:{}", docNumber, docName, page);

        //需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
     /*   List<Integer> brandIds = null;*//*
        *//*if (adminDataAuthService.isBrandManager()) {*//*
    *//*        brandIds = adminDataAuthService.getBrandIds();
            logger.info("运营商管理角色操作，需控制数据权限，brandIds:{}",JSONObject.toJSONString(brandIds));

            if (brandIds == null || brandIds.size() == 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0L);
                data.put("items", null);

                logger.info("【请求结束】商品管理->商品管理->查询,响应结果:{}", JSONObject.toJSONString(data));
                return ResponseUtil.ok(data);
          *//**//*  }*//*
   *//*     }*/

        return adminDocService.list(docNumber,docName, page, limit, sort,order);
    }

/*    @GetMapping("/catAndBrand")
    public Object catAndBrand() {
        return adminDocService.catAndBrand();
    }*/

    /**
     * 编辑商品
     *
     * @param docAll
     * @return
     */
    @RequiresPermissions("admin:doc:update")
    @RequiresPermissionsDesc(menu = { "文件管理", "文件列表" }, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody DocAll docAll) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 文件管理->文件列表->编辑,请求参数:{}", JSONObject.toJSONString(docAll));

        return adminDocService.update(docAll);
    }

    /**
     * 删除文件
     *
     * @param doc
     * @return
     */
    @RequiresPermissions("admin:doc:delete")
    @RequiresPermissionsDesc(menu = { "文件管理", "文件列表" }, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody GmDoc doc) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 文件管理->文件管理->删除,请求参数:{}", JSONObject.toJSONString(doc));

        return adminDocService.delete(doc);
    }

    /**
     * 添加商品
     *
     * @param docAll
     * @return
     */
    @RequiresPermissions("admin:doc:create")
    @RequiresPermissionsDesc(menu = { "文件管理", "文件列表" }, button = "新增")
    @PostMapping("/create")
    public Object create(@RequestBody DocAll docAll) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 文件管理->文件列表->新增,请求参数:{}", JSONObject.toJSONString(docAll));
        GmDoc doc = docAll.getDoc();
        String certifytime = doc.getCertifyTime().toString().substring(0, 9)/*.replaceAll("T"," ")*/;
        String draftstime = doc.getDraftsTime().toString().substring(0, 9)/*.replaceAll("T"," ")*/;
        String reviewtime = doc.getReviewTime().toString().substring(0, 9)/*.replaceAll("T"," ")*/;
        String addTime = doc.getReviewTime().toString().substring(0, 9);
        String updateTime = doc.getReviewTime().toString().substring(0, 9);
        logger.info(certifytime + certifytime + certifytime);
        ZoneId zone = ZoneId.systemDefault();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份
        LocalDate ct = null;
        LocalDate dr = null;
        LocalDate rv = null;
        LocalDate ad = null;
        LocalDate up = null;
        try {
            Date dct = simpleDateFormat.parse(certifytime);
            Date dad = simpleDateFormat.parse(addTime);
            Date ddr = simpleDateFormat.parse(draftstime);
            Date drv = simpleDateFormat.parse(reviewtime);
            Date dup = simpleDateFormat.parse(updateTime);

            ct = LocalDateTime.ofInstant(dct.toInstant(), zone).toLocalDate();
            ad = LocalDateTime.ofInstant(dad.toInstant(), zone).toLocalDate();
            dr = LocalDateTime.ofInstant(ddr.toInstant(), zone).toLocalDate();
            rv = LocalDateTime.ofInstant(drv.toInstant(), zone).toLocalDate();
            up = LocalDateTime.ofInstant(dup.toInstant(), zone).toLocalDate();

        } catch (ParseException e) {
            e.printStackTrace();
        }

        doc.setCertifyTime(ct);
        doc.setDraftsTime(dr);
        doc.setReviewTime(rv);
        doc.setAddTime(ad);
        doc.setUpdateTime(up);

        Random randomno = new Random();
        Integer id = new Integer(10000);
        doc.setDocType(new Integer(3424));
        doc.setId(2323);
        doc.setDeleted(false);

        doc.setIseffective(true);
        docAll.setDoc(doc);
        logger.info(doc.getCertifyTime().toString());
        logger.info(doc.toString());
        return adminDocService.create(docAll);
    }

    /**
     * 文件详情
     *
     * @param id
     * @return
     */
    @RequiresPermissions("admin:doc:read")
    @RequiresPermissionsDesc(menu = { "文件管理", "文件列表" }, button = "详情")
    @GetMapping("/detail")
    public Object detail(@NotNull Integer id) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 文件管理->文件管理->详情,请求参数,id:{}", id);

        return adminDocService.detail(id);
    }

}
